package com.keyue.common.utils;

import cn.hutool.core.util.IdUtil;
import com.keyue.common.constant.ServerResultCode;
import com.keyue.common.exception.BusinessException;
import com.keyue.security.config.SecurityProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;


@Slf4j
@Service
public class ImgCaptchaUtils {

    @Resource
    private SecurityProperties properties;

    @Resource
    private RedisUtil redisUtil;

    @Value("${loginCode.expiration}")
    private Long expiration;

    /**
     * @param imgCaptchaCode
     * @param imgCaptchaUuid
     */
    public void validateImgCaptcha(String imgCaptchaCode, String imgCaptchaUuid) {
        // 查询验证码
        String code = redisUtil.get(imgCaptchaUuid);
        // 清除验证码
        redisUtil.delete(imgCaptchaUuid);
        if (StringUtils.isBlank(code)) {
            throw new BusinessException(ServerResultCode.IMG_CAPTCHA_EXPIRE_ERROR);
        }
        if (StringUtils.isBlank(imgCaptchaCode) || !imgCaptchaCode.equalsIgnoreCase(code)) {
            throw new BusinessException(ServerResultCode.IMG_CAPTCHA_ERROR);
        }
    }

    /**
     * @param imgCaptchaCode
     * @return
     */
    public String setImgCaptcha4uuid(String imgCaptchaCode) {
        String uuid = properties.getCodeKey() + IdUtil.simpleUUID();
        // 保存
        redisUtil.set(uuid, imgCaptchaCode, expiration, TimeUnit.MINUTES);
        return uuid;
    }

}
